import click

from watchlist import app, db
from watchlist.models import User, Message_History
from datetime import datetime
from watchlist.utils import tools

@app.cli.command()  # 注册为命令，可以传入 name 参数来自定义命令
@click.option('--drop', is_flag=True, help='Create after drop.')  # 设置选项
def initdb(drop):
    """Initialize the database."""
    if drop:  # 判断是否输入了选项
        db.drop_all()
    db.create_all()
    click.echo('初始化数据库完成')

# 插入假数据到数据库
@app.cli.command()
def forge():
    """Generate fake data."""
    db.create_all() #使用模型创建表
    name = 'Grey Li'
    user = User(name=name)
    db.session.add(user)
    db.session.commit()
    click.echo('插入假数据完成')

        
# 清空会话记录
@app.cli.command()
def clearhistory():
    """Clear all records from the Message_History table."""
    try:
        db.session.query(Message_History).delete()
        db.session.commit()
        click.echo('Message_History 表已清空')
    except Exception as e:
        db.session.rollback()  # 回滚事务
        click.echo(f'清空 Message_History 表时出错: {e}')


# 创建管理员
@app.cli.command()
@click.option('--username', prompt=True, help='The username used to login.')
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True, help='The password used to login.')
@click.option('--userrole', prompt=True, help='user/admin/visitor')
def admin(username, password, userrole):
    """Create user."""
    db.create_all()

    user = User.query.first()
    if user is not None:
        click.echo('Updating user...')
        user.username = username
        user.set_password(password)  # 设置密码
    else:
        click.echo('Creating user...')
        user = User(username=username, name='Admin')
        user.set_password(password)  # 设置密码
        user.set_userrole(userrole)  # 设置角色
        user.set_createtime(tools.getNowTime())
        db.session.add(user)

    db.session.commit()  # 提交数据库会话
    click.echo('创建管理员成功')
